const WebSocket = require("ws");

let wssInstance = null;

function createWebSocketServer(server) {
  if (!wssInstance) {
    wssInstance = new WebSocket.Server({ server });
    wssInstance.on("connection", (ws) => {
      console.log("WebSocket client connected");
      ws.on("message", (message) => {
        console.log("received:", message);
      });
    });
  }

  return wssInstance;
}

function getWebSocketServer() {
  if (!wssInstance) {
    throw new Error("WebSocket server not initialized");
  }
  return wssInstance;
}

module.exports = {
  createWebSocketServer,
  getWebSocketServer,
};
